package com.gome.ocean.controller.authority;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.ProjectBO;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.service.authority.ProjectService;
import com.gome.ocean.service.authority.UserService;
import com.gome.ocean.service.base.BaseController;
import com.gome.ocean.service.diamond.ConfigInfoService;
import com.google.common.collect.Lists;

/**
 * Created by liuqingxia on 2016/3/2.
 */
@Controller
public class ProjectController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);
    @Autowired
    private ProjectService      projectService;
    @Autowired
    private ConfigInfoService   configInfoService;
    @Autowired
    private UserService         userService;

    private final String PROJECT_NAME         = "projectName";
    private final String PROJECT_PHONE        = "projectPhone";
    private final String PROJECT_USER         = "projectUsers";
    private final String PROJECT_EMAIL        = "projectEmail";
    private final String PROJECT_ID           = "id";
    private final int    DEFAULT_MAX_USER_ROW = 500;
    private final int    DEFAULT_MIN_USER_ROW = 1;

    @RequestMapping(value = "/admin/project/insert", method = RequestMethod.GET)
    public String insertGet(ModelMap m) {
        List<String> emails = Lists.newArrayList();
        try {
            Page<User> users = userService.findAllUser(DEFAULT_MIN_USER_ROW, DEFAULT_MAX_USER_ROW);
            for (User user : users) {
                emails.add(user.getEmail());
            }
            m.put("emails", emails);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            m.put("errorMsg", "查询用户过程中发生异常，请查看服务器日志");
            return "project/insert";
        }
        return "project/insert";
    }

    @RequestMapping(value = "/admin/project/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insertPost(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        String errorMsg = validateParam(req);
        if (StringUtils.isNotBlank(errorMsg)) {
            return page.setErrorMsg(errorMsg);
        }
        ProjectBO project = getProjectFormRequest(req);
        try {
            if (projectService.insertProject(project)) {
                return page.setSuccessMsg("新建工程组成功");
            } else {
                return page.setErrorMsg("新建工程组失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/admin/project/remove", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage remove(@RequestParam("id") long id) {
        ResponsePage page = new ResponsePage();
        if (id <= 0) {
            return page.setErrorMsg("id不能小于等于0");
        }
        try {
            if (projectService.removeProjectById(id)) {
                return page.setSuccessMsg("删除成功");
            } else {
                return page.setErrorMsg("删除失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/admin/project/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage update(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        String errorMsg = validateParam(req);
        if (StringUtils.isNotBlank(errorMsg)) {
            return page.setErrorMsg(errorMsg);
        }
        ProjectBO project = getProjectFormRequest(req);
        try {
            if (projectService.updateProject(project)) {
                return page.setSuccessMsg("更新项目组成功");
            } else {
                return page.setErrorMsg("更新项目组失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/admin/project/find", method = RequestMethod.GET)
    public String findGet(ModelMap m) {
        List<String> emails = Lists.newArrayList();
        try {
            Page<User> users = userService.findAllUser(DEFAULT_MIN_USER_ROW, DEFAULT_MAX_USER_ROW);
            for (User user : users) {
                emails.add(user.getEmail());
            }
            m.put("emails", emails);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            m.put("errorMsg", "查询用户过程中发生异常，请查看服务器日志");
            return "project/find";
        }
        return "project/find";
    }

    @RequestMapping(value = "/admin/project/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findPost(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        if (!StringUtils.isBlank(req.getParameter(PROJECT_NAME))) {
            return findByName(req);
        }
        int pageNum = super.getPageNumFromRequest(req);
        int pageSize = super.getPageSizeFromRequest(req);
        try {
            Page projects = projectService.findAllProjects(pageNum, pageSize);
            if (projects != null && !projects.isEmpty()) {
                return page.setPage(projects, "查询成功");
            } else {
                return page.emptyPage("未查询到结果");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/project/findById", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findById(@RequestParam("id") long id) {
        ResponsePage page = new ResponsePage();
        if (id <= 0) {
            return page.setErrorMsg("id不能小于0");
        }
        try {
            ProjectBO project = projectService.findProjectById(id);
            if (null != project) {
                return page.setSingleObject(project, "查询成功");
            } else {
                return page.setErrorMsg("查询失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/project/findByName", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findByName(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        String projectName = req.getParameter(PROJECT_NAME);
        if (StringUtils.isBlank(projectName)) {
            return page.setErrorMsg("projectName不能为空");
        }
        try {
            ProjectBO project = projectService.findProjectByName(projectName);
            if (project == null) {
                return page.setErrorMsg("数据库中未查询到此条记录，projectName=" + projectName);
            } else {
                return page.setSingleObject(project, "查询成功");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/project/findByUser", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findByUser(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        String projectUser = req.getParameter(PROJECT_USER);
        if (StringUtils.isBlank(projectUser)) {
            return page.setErrorMsg("projectUser不能为空");
        }
        try {
            List<ProjectBO> projects = projectService.findProjectByUser(projectUser);
            if (projects != null && !projects.isEmpty()) {
                return page.setJustList(projects, "查询成功");
            } else {
                return page.setErrorMsg("查询失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/project/findAllAppName", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findAllAppName(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        try {
            List<String> appNames = configInfoService.findShortAllApp();
            if (appNames != null && !appNames.isEmpty()) {
                return page.setJustList(appNames, "查询成功");
            } else {
                return page.setErrorMsg("查询失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    private String validateParam(HttpServletRequest req) {
        String projectName = req.getParameter(PROJECT_NAME);
        if (StringUtils.isBlank(projectName)) {
            return "请输入项目组名";
        }
        String projectUsers = req.getParameter(PROJECT_USER);
        if (StringUtils.isBlank(projectUsers)) {
            return "请选择项目组成员";
        }
        String[] projectUserArr = projectUsers.split(Constants.REG_CN_OR_EN_COMMA);
        for (String projectUser : projectUserArr) {
            if (!projectUser.matches(Constants.REG_EMAIL)) {
                return "用户名格式不正确，正确格式为：xxx@gomeplus.com";
            }
        }
        String projectEmail = req.getParameter(PROJECT_EMAIL);
        if (StringUtils.isBlank(projectEmail)) {
            return "请指定项目组负责人邮箱";
        }
        if (!projectEmail.matches(projectEmail)) {
            return "项目组负责人Email格式不正确，正确格式为：xxx@gomeplus.com";
        }
        String projectPhone = req.getParameter(PROJECT_PHONE);
        if (StringUtils.isBlank(projectPhone)) {
            return "请输入项目组负责人联系电话";
        }
        if (!projectPhone.matches(Constants.REG_PHONE_NUMBER)) {
            return "电话号码格式不正确";
        }
        return null;
    }

    /**
     * 调用此方法前需先调用validateParam(HttpServletRequest req)
     * 
     * @param req
     * @return
     */
    private ProjectBO getProjectFormRequest(HttpServletRequest req) {
        String projectName = req.getParameter(PROJECT_NAME);
        String projectUsers = req.getParameter(PROJECT_USER);
        String projectEmail = req.getParameter(PROJECT_EMAIL);
        String projectPhone = req.getParameter(PROJECT_PHONE);
        ProjectBO project = new ProjectBO(projectName, projectUsers, projectEmail, projectPhone);
        String projectIdStr = req.getParameter(PROJECT_ID);
        if (!StringUtils.isBlank(projectIdStr)) {
            long projectId = Long.parseLong(projectIdStr);
            project.setId(projectId);
        }
        return project;
    }

}
